#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @FileName  :api_02.py
# @Time      :2024/11/9 0:44
# @Author    :zhou_yi
import base64
from fastapi import APIRouter, UploadFile, File, Form
from service.fn_db import addressDB, addressFS
from models.BaseModels import PointBaseModel

a02 = APIRouter()


# 名称查询点位
@a02.get('/point/{point}')
async def fetch_address_by_point(point: str) -> PointBaseModel:
    _res: dict = await addressDB.fetch_by_point(point=point)
    point = PointBaseModel(**_res)
    return point


# 对应图片base64编码
@a02.get('/point_imgs/{piontID}')
async def fetch_address_imgs_by_pointID(pointID: str):
    _res: list[dict] = await addressFS.fetch_many_by_pointID(pointID)
    bs64_lst: list = [base64.b64encode(r['content']).decode('utf-8') for r in _res]
    return bs64_lst


# 客户名称查询点位
@a02.get('/points/{custom}')
async def fetch_address_by_custom(custom: str) -> list[PointBaseModel]:
    _res = await addressDB.fetch_by_custom(custom=custom)
    points = [PointBaseModel(**itm) for itm in _res]
    return points


# 集合中最大的id 与新id
@a02.get('/address_max_and_new_id')
async def address_max_and_new_id() -> list[str]:
    _tuple = await addressDB.max_id_and_new_id()
    return list(_tuple)


# 插入一条点位记录
@a02.post('/point')
async def insert_one_point(point: PointBaseModel):
    res = await addressDB.insert_one(point.dict())
    if res:
        return point.id
    else:
        return False


# 插入点位的图片存入数据库
@a02.post('/point_imgs/{pointId}')
async def insert_one_point_images(pointId: str, files: list[UploadFile] = File(...)):
    if files:
        data = [await f.read() for f in files]  # 数据流列表
        res: int = await addressFS.insert_many_by_pointID(pointId, data)  # 存入数据库
        return res  # 文件的数量
    else:
        return False


# 修改点位
@a02.put('/point/{pointName}')
async def update_point(pointName: str, data: dict):
    _res = await addressDB.update_one({'point': pointName}, data)
    return _res


# 删除点位
@a02.delete('/point/{pointName}')
async def delete_point(pointName: str):
    # 删除数据
    _res = await addressDB.delete_one({'point': pointName})
    # 删除图片
    _nums=await addressFS.delete_many_by_pointID(pointID=_res[2])

    return list((_res, _nums))


# 插入多条点位记录
@a02.post('/points')
async def insert_many_point(points: list[PointBaseModel]):
    points = [itm.dict() for itm in points]
    res: bool = await addressDB.insert_many(points)
    return res


if __name__ == '__main__':
    ...
